<template>
	<view>
        <view class="u-page commonpopup">
            <view class="innerBoxer commonPopInfo" v-if="globalConfig && commonPopupInfo">
                <view class="label" :style="globalConfig.globalStyle.popupLabelStyle">
                	{{commonPopupInfo.popupInfo.label}}</view>
                <view class="body">    
                	<view class="formPage" v-if="formItems && model">
                		<u--form labelPosition="left" :model="model" ref="form1" reef="form1">
                			<view v-for="(item, index) in formItems" :key="index" class="fieldItem"
                				:class="{candelete: item.candelete}" v-show="!item.hide">
                				<view v-if="item.type == 'text'"
                					:class="[item.prop, {address: item.address, hasBtn: item.prop == 'dxyzNo' || item.autho}]">
                					<u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="commonPopupInfo.popupInfo.showRequireStar && item.required"
                						@click="openPicker(item)">
                						<u--input v-model="model[item.prop]" :placeholder="item.placeholder"
                							border="none" :readonly="item.readonly"></u--input>
                						<view class="getcode" v-if="item.prop == 'dxyzNo'">
                							<u-button @tap="getCode" type="success" :disabled="validateBtnDisabled"
                								size="small">{{ validateTips }}</u-button>
                						</view>
                
                						<view class="getcode" v-if="item.autho == 'faceValidate'">
                							<u-button @tap="startFaceValidate(item)" type="success"
                								size="small">点击认证</u-button>
                						</view>
                						<view class="getcode" v-if="item.autho == 'phone'">
                							<u-button open-type="getPhoneNumber"
                								@getphonenumber="getPhoneNumber($event, item)" type="success"
                								size="small">授权手机号</u-button>
                						</view>
                					</u-form-item>
                				</view>
                                <view v-else-if="item.type == 'date' || item.type == 'time' || item.type == 'carNo' || item.type == 'tree-picker'">
                                    <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="commonPopupInfo.popupInfo.showRequireStar && item.required" @click="openPicker(item)">
                                        <u--input placeholder-class="pcs" v-model="model[item.prop]" :placeholder="item.placeholder" border="none" disabled></u--input>
                                        <u-icon slot="right" name="arrow-right"></u-icon>
                                    </u-form-item>
                                </view>
                                <view v-else-if="item.type == 'picker'">
                                    <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="commonPopupInfo.popupInfo.showRequireStar && item.required" @click="openPicker(item)">
                                        <u--input v-model="model[item.prop]" :placeholder="item.placeholder" border="none" disabled></u--input>
                                        <u-icon slot="right" name="arrow-right"></u-icon>
                                    </u-form-item>
                                    <my-u-picker immediateChange :show="item.showPicker" keyName="name" :ref="item.prop + 'Picker'" 
                                    :columns="item.columns" @confirm="openPickerConfirm($event, item)"
                                    @cancel="onPickerClose(item)" @close="onPickerClose(item)" closeOnClickOverlay></my-u-picker>
                                </view>
                                <view v-else-if="item.type == 'xq-picker'">
                                    <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="commonPopupInfo.popupInfo.showRequireStar && item.required" @click="openPicker(item)">
                                        <u--input v-model="model[item.prop]" :placeholder="item.placeholder" border="none" disabled></u--input>
                                        <u-icon slot="right" name="arrow-right"></u-icon>
                                    </u-form-item>
                                </view>
                				<view v-else-if="item.type == 'checkbox'" v-show="!item.hide"
                					:class="[item.prop]">
                					<u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" :required="commonPopupInfo.popupInfo.showRequireStar && item.required">
                						<view class="options">
                							<view class="option" v-for="(op, opindex) in item.options" :key="opindex" :class="{ active: op.active }" @click="optionChecked(item, opindex)">
                								{{ op.name }}
                							</view>
                						</view>
                					</u-form-item>
                				</view>
                
                			</view>
                		</u--form>
                        <u-datetime-picker @confirm="datePickerConfirm" @close="showDatePicker = false" 
                        :maxDate="maxDate" :minDate='minDate'
                        @cancel="showDatePicker = false" :show="showDatePicker" :value="datePickerModel" mode="date" closeOnClickOverlay></u-datetime-picker>
                        <my-u-picker :show="showXqPicker" keyName="name" ref="xqPicker" reef="xqPicker" :columns="xqColumns" @confirm="onXqConfirm" @change="onXqChange" @cancel="showXqPicker = false" @close="showXqPicker = false" closeOnClickOverlay></my-u-picker>
                	</view>




                	<u-code :seconds="30" ref="uCode" reef="uCode" @change="codeChange" change-text="XS获取"
                		@start="validateBtnDisabled = true" @end="validateBtnDisabled = false"></u-code>
                </view>
            </view>

            <view class="innerBoxer commonPopInfo">
                <view class="label" :style="globalConfig.globalStyle.popupLabelStyle">申请人家庭成员情况
                    <view class="addNew" @click="addJtcy()"><view>+</view></view>
                </view>
                 <view class="body">    
                	<view class="formPage _ext">
                    <view class="txry" v-for="(jtcyItem, jtcyIndex) in jtcyArray" :key="jtcyIndex" v-show="!jtcyItem.deleted">
                        <u--form labelPosition="left"
                            :model="jtcyItem.model" :ref="'jtcyForm' + jtcyIndex" :reef="'jtcyForm' + jtcyIndex">
                            <view :class="item.prop" v-for="(item, index) in jtcyItem.formItems" :key="index">
                                <u-form-item :label="item.label" :prop="item.prop" borderBottom labelWidth="120" >
                                    <u--input v-model="jtcyItem.model[item.prop]" :placeholder="item.placeholder" border="none" :readonly="item.readonly"></u--input>
                                </u-form-item>
                            </view>
                            <view class="delete-btn"><u-button type="error" size="mini" text="删除" @click="deleteJytc(jtcyItem)"></u-button> </view>
                        </u--form>
                        <u-divider :dot="true"></u-divider>
                    </view>
                </view>
                </view>
            </view>


            <view class="confirmArea">
                <text class="textarea" space="emsp"
                	v-if="commonPopupInfo.popupInfo.text">{{commonPopupInfo.popupInfo.text}} </text>
                <view class="checkbox" v-if="commonPopupInfo.popupInfo.wait">
                	请先仔细阅读上文，还剩{{commonPopupInfo.popupInfo.wait}}秒
                </view>
                <view class="checkbox"
                	v-if="!commonPopupInfo.popupInfo.wait && commonPopupInfo.popupInfo.showConfirm">
                	<u-checkbox-group v-model="commonPopupInfo.popupInfo.comfirm" placement="column"
                		@change="commonPopupCheckboxChanged">
                		<u-checkbox :customStyle="{marginBottom: '8px'}" shape="circle" name="readbeforeConfirm"
                			:label="commonPopupInfo.popupInfo.confirmText">
                		</u-checkbox>
                	</u-checkbox-group>
                    <view class="gaozhiBook" v-if="commonPopupInfo.popupInfo.gaozhiBook" @click="showModelGz">
                        {{commonPopupInfo.popupInfo.gaozhiBook.name}}
                    </view>
                </view>
            </view>
            
            <view class="confirmBtn">
            	<u-button type="primary" @click="submit()"
            		:disabled="commonPopupInfo.popupInfo.wait || commonPopupInfo.popupInfo.showConfirm && !commonPopupInfo.popupInfo.confirm">
            		{{commonPopupInfo.popupInfo.confirmBtnText || '确定'}}</u-button>
            </view>
        </view>
	</view>
</template>
<script>
	import { mapState, mapMutations } from 'vuex';
	import sceneMixins from '@/utils/sceneMixins';
    import formMixins from '@/utils/formMixins.js'
    import xqPickerMixins from '@/utils/xqPickerMixins.js'
    import WXBizDataCrypt from '@/utils/WXBizDataCrypt.js'
    import mytabbar from '@/components/tabbar/index.vue' 
    import formUtils from '@/utils/formUtils.js';
	export default {
		options: { styleIsolation: 'shared' },
        components: {mytabbar: mytabbar},
		mixins: [formMixins, xqPickerMixins, sceneMixins],
		computed: {
			...mapState(['userInfo', 'globalConfig'])
		},
		data() {
            var currentTime = new Date().getTime();
            var minTime = new Date().setYear(0);
			return {
                commonPopupInfo: '',
                firstShow: true,
                maxDate: currentTime,
                minDate: minTime,


                jtcyArray: [],
                jtcyModel: {},
			}
		},
		onLoad() {
            var vm = this;
            uni.login({
                provider: 'weixin',
                success: function (res) {
                    console.log(res);
                }
            });
            var vm = this;
            vm.doWxLogin().then(res => {
                vm.openId = res.openId;
            });
            vm.waitVariable('globalConfig').then(() => {
                vm.getXqColumns();
                vm.commonPopupInfo = {
                    popupInfo: JSON.parse(JSON.stringify(vm.globalConfig.registerForm))
                };
                var formItems = JSON.parse(JSON.stringify(vm.commonPopupInfo.popupInfo.form));
                if (vm.commonPopupInfo.popupInfo.wait) {
                	if (process.env.NODE_ENV == 'development') {
                		vm.commonPopupInfo.popupInfo.wait = 3;
                	}
                	global.beforeWaitTo = setInterval(() => {
                		if (vm.commonPopupInfo.popupInfo.wait) {
                			vm.commonPopupInfo.popupInfo.wait--
                		} else {
                			clearInterval(global.beforeWaitTo);
                		}
                	}, 1000);
                }
                if (this.firstShow) {
                	formItems.forEach(n => {
                		if (!n.prop) {
                		    return;
                		}
                		n.value = '';
                		if (n.optionApi && !n.lazySearch) {
                		    n.optionApi = n.optionApi.replace('【openId】', vm.openId);
                		    vm.getAndLoad('读取option列表', n.optionApi, function (res) {
                		        n.options = res.data;
                		        if (n.type == 'picker') {
                		            n.columns = [n.options];
                		        }
                		    });
                		} else if (n.type == 'picker' && n.options) {
                		    n.columns = [n.options];
                		}
                		// 设置一些初始值
                		if (n.type == 'checkbox') {
                		    if (!n.options.map) {
                		        n.options = n.options.split('$').map((m, i) => {
                		            return {
                		                name: m.split(':')[1],
                		                active: !i,
                		                value: m.split(':')[0],
                		            };
                		        })
                		    } else {
                		        n.options = n.options.map((o, i) => {
                		            return { name: o, active: !i };
                		        });
                		    }
                		}
                		if (n.type == 'picker') {
                		    n.showPicker = false;
                		}
                		if (n.type == 'areapicker') {
                		    n.provinceCityArea = [];
                		}
                		if (n.type == 'image') {
                		    !n.limit && (n.limit = 1);
                		    n.fileList = [];
                		}
                	});
                    vm.formItems = formItems;
                	vm.$nextTick(() => {
                		vm.generateModelAndRules();
                	});
                	this.firstShow = false;
                }
            })
		},
		methods: {
			...mapMutations(['doLogin']),
            commonPopupCheckboxChanged: function (data) {
                this.commonPopupInfo.popupInfo.confirm = data.length;
            },
            showModelGz: function () {
                var title = this.commonPopupInfo.popupInfo.gaozhiBook.name;
                var content = this.commonPopupInfo.popupInfo.gaozhiBook.content;
                if (title) {
                    uni.showModal({
                        title: title,
                        content: content,
                        showCancel: false,
                    });
                }
            },
            deleteJytc (item) {
                item.deleted = true;
            },
            addJtcy () {
            
                var vm = this;
                var jtcyItem = {
                    deleted: false,
                    formItems: JSON.parse(JSON.stringify(vm.globalConfig.txryFormItems))
                };
                var currentIndex = vm.jtcyArray.length;
                var {rules, model} = formUtils.generateModelAndRules(jtcyItem.formItems);
                jtcyItem.formName = 'jtcyForm' + currentIndex;
                jtcyItem.model = model;
                vm.jtcyArray.push(jtcyItem);

                vm.$nextTick(function(){
                    setTimeout(() => {
                        vm.getRefCmp(jtcyItem.formName).setRules(rules);
                    }, 1000);
                });
            },
			submit: function () {
				var vm = this;
				console.log(this.model);
				var form1 = vm.getRefCmp('form1');
				form1.validate().then(() => {
					var model = JSON.parse(JSON.stringify(vm.model));
					model.openId = vm.openId;
					var postUrl = vm.commonPopupInfo.popupInfo.loginApi;
					vm.getAndLoad('保存', postUrl + vm.$Util.stringify(model), function(res) {
						uni.hideLoading();
						if (res.code == 0) {
							uni.$u.toast('注册成功！');
							if (model.faceValidate) {
								vm.model.rz = true;
							}
							vm.doLogin(JSON.parse(JSON.stringify(vm.model)));
                            uni.navigateTo({
                                url: '/pages/mine/index'
                            })
						} else {
							uni.$u.toast(res.msg || '注册失败');
						}
					});
				});
			},

			getPhoneNumber: function(e, item) {
				var vm = this;
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					this.doWxLogin(true).then(res => {
						var pc = new WXBizDataCrypt(vm.globalConfig.appId, res.sessionKey);
						var phone = pc.decryptData(e.detail.encryptedData, e.detail.iv);
						vm.model[item.prop] = phone.phoneNumber;
					});
				} else {
                    uni.$u.toast('无法获取, 需手动输入');
					console.log('用户点击了拒绝');
				}
			},
			startFaceValidate: function (item) {
				var vm = this;
				var form1 = vm.getRefCmp('form1')
				form1.validateField(item.getProp[0], function(r1) {
					form1.validateField(item.getProp[1], function(r2) {
						if (!r1.length && !r2.length) { 
							wx.startFacialRecognitionVerify({
								name: vm.model[item.getProp[1]],
								idCardNumber: vm.model[item.getProp[0]],
								complete: function (res) {
									if (res.errCode == 0) {
										item.autho = '';
										vm.$set(vm.model, item.prop, '认证已通过');
										vm.formItems.find(n => n.prop == item.getProp[1]).readonly = true;
										vm.formItems.find(n => n.prop == item.getProp[0]).readonly = true;
									}
								}
							})
						}
					});
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
    .commonPopInfo {
        width: 690rpx;
        background: #fff;
        border-radius: 16rpx;
        margin-left: 30rpx;
        margin-top: 50rpx;
        >.label {
            height: 90rpx;
            line-height: 90rpx;
            text-indent: 30rpx;
            font-weight: bold;
        }

        .textarea {
            max-height: 700rpx;
            overflow-y: scroll;
            font-size: 26rpx;
            padding: 10rpx 30rpx;
            display: block;
        }

        .body {
            background: #fff;
            border-radius: 0 0 20rpx 20rpx;
            overflow: hidden;
        }
    }

    .innerBoxer {
        position: relative;
        .addNew {
            position: absolute;
            right: 10px;
            top: 8px;
            width: 20px;
            height: 20px;
            border: 2px solid #0053ff;
            color: #0053ff;
            line-height: 40px;
            font-size: 24px;
            text-align: center;
            justify-content: center;
            border-radius: 50%;
            view {
                position: absolute;
                right: 0;
                top: -11px;
            }
        }
    }
    .confirmArea {
        margin: 30rpx 20rpx;
        .checkbox {
        	padding: 10px 20rpx 0;
        	zoom: 0.9;
            display: flex;
            align-items: center;
            .gaozhiBook {
                font-size: 26rpx;
                margin-top: -16rpx;
                color: #477cf3;
            }
        }
    }
    
        
    .confirmBtn {
    	padding: 0 30rpx 20rpx;
        margin: 70rpx 30rpx 0;
    }
    .formPage {
        margin: 20rpx 0;
        width: 100%;
        min-height: 300rpx;
        padding: 0 20rpx;
        box-sizing: border-box;
        &._ext {
            min-height: unset;
            /deep/ .u-form {
                position: relative;
                .delete-btn  {
                    position: absolute;
                    right: 10rpx;
                    top: 5rpx;
                    z-index: 10;
                }
            }

        }
        .fieldItem {
            position: relative;

            &.candelete {
                padding-top: 40rpx;
                background: #fff;
            }

            .delete-btn  {
                position: absolute;
                right: 10rpx;
                top: 5rpx;
            }
        }

        /deep/ {
            .u-form-item {
                background: #fff;
                padding: 0 20rpx 0 30rpx;
            }

            .uni-input-input {
                text-align: left !important;
                font-size: 28rpx !important;
            }

            .u-input {
                background: transparent !important;
            }

            .u-form-item__body__right__message {
                text-align: right;
            }

            .u-upload__wrap {
                margin-left: auto;
            }

            .uni-input-placeholder {
                text-align: left !important;
                font-size: 28rpx !important;
            }

            .u-form-item__body__left__content__label {
                font-size: 28rpx;
            }

            .u-input__content__field-wrapper__field {
                text-align: left !important;
                font-size: 28rpx !important;
            }

            .u-form-item__body__right__content__slot {
                display: flex;
                flex-direction: row;

                region-picker {
                    width: 100%;
                }
            }

            .textareaField {
                .u-form-item__body__right__content__slot {
                    display: flex;
                    flex-direction: column;
                }
            }

            .hasBtn {
                .u-form-item__body__right__content__slot {

                    // display: flex;
                    // flex-direction: row;
                    >.u-input--square {
                        width: 50%;
                    }

                    .getcode {
                        margin-left: 10px;
                        width: 160rpx;
                    }
                    .u-button--small {
                        font-size: 24rpx;
                    }
                }
            }

            .getAddress {
                padding: 0 10rpx;
            }
        }

        .gap {
            color: #999999;
            text-indent: 10px;
            margin: 10rpx 0;
            font-size: 28rpx;

            &.line {
                border-bottom: 1px solid #999999;
            }

            &.dashed {
                border-bottom: 1px dashed #999999;
            }
        }

        .text-area-label {
            font-size: 28rpx;
            line-height: 60rpx;
            color: #303133;
            margin: -10rpx 0 0 -2rpx;
            position: relative;

            .require {
                font-size: 20px;
                color: #f56c6c;
                position: absolute;
                left: -16rpx;
                top: 5rpx;
            }

            .subLabel {
                font-size: 20rpx;
            }
        }

    }
    .options {
        display: flex;
        margin-left: auto;
        flex-wrap: wrap;
        .option {
            color: #fff;
            min-width: 60rpx;
            text-align: center;
            background: #afabab;
            padding: 4rpx 10rpx;
            border-radius: 16rpx;
            margin-right: 10rpx;
            margin-bottom: 6rpx;
            font-size: 24rpx;
            &.active {
                background: #2788f3;
            }
        }
    }
</style>
